package xiancheng_tongxin;

public class TestDemo {
    //实现生产者和消费者的步骤：
    /*
    *
    *
    * */
    public static final Stack stack = new Stack();//创建栈对象

    public static void main(String[] args) {
        //创建商品对象
        Product p = new Product();
        //创建消费者线程
        Customer c = new Customer(stack);
        //创建生产者线程
        Producer p1 = new Producer(stack);

        //创建线程
        //当有多个线程会进入阻塞时，会发生死锁，或者为空，那么我们只能牺牲一些性能，使用notifyAll()方法
        Thread t1 = new Thread(c, "消费者");
        Thread t0 = new Thread(c, "消费者");
        t1.start();
        t0.start();
        Thread t2 = new Thread(p1, "生产者");
        Thread t3 = new Thread(p1, "生产者");
        t3.start();
        t2.start();
    }
}

//创建消费者线程
class Customer implements Runnable {
    private Stack stack;

    public Customer(Stack stack) {
        this.stack = stack;
    }

    @Override
    public void run() {
        while (true) {
            stack.pop();
        }
    }
}

//创建生产者线程
class Producer implements Runnable {
    private Stack stack;

    public Producer(Stack stack) {
        this.stack = stack;
    }
    @Override
    public void run() {
        int i = 1;
        while (true) {
            if (i % 2 == 0) {
                stack.push(new Product("白色", "手坤"));
            } else {
                stack.push(new Product("黑色", "篮球"));
            }
            i++;
        }
    }
}